<?php

namespace Admin\Model;

use Think\Model;

class OrgModel extends Model {

    protected $tableName = 'org';
    protected $pk = 'id';

    //保存设置
    public function getOrgTree($id) {
        if (isset($id)) {
            $list = $this->field("*")->where("id <>" . $id)->select();
        } else {
            $list = $this->field("*")->select();
        }
        return $this->dataTree($list);
    }

    private function dataTree($data, $parentid = 0, $level = 1) {
        if ($data) {
            $childData = $this->getChild($data, $parentid);
            $count = count($childData); //当前子栏目个数
            $level++; //子栏目层级
            foreach ($data as $v) {
                if ($v['pid'] == $parentid) {
                    $index++;
                    if ($count == $index)
                        $step = "└─";
                    else
                        $step = "├─";
                    $step.='&nbsp;&nbsp;';
                    $nbsp = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $level - 1);
                    $nstr = $nbsp . $step;
                    if ($parentid == 0)
                        $nstr = '';
                    $v['step'] = $nstr;
                    $newData[$v['id']] = $v;
                    $dataChild = $this->dataTree($data, $v['id'], $level);
                    if (!empty($dataChild)) {
                        $newData = $newData + $dataChild;
                    }
                }
            }
        }

        return $newData;
    }

    private function getChild($data, $parentid = 0) {
        $newData = array();
        foreach ($data as $v) {
            if ($v['pid'] == $parentid) {
                $newData[] = $v;
            }
        }
        return $newData;
    }

}
